package lc;
import java.util.*;
import org.junit.*;
public class Ex661 {
    class Solution {
        public int triangleNumber(int[] nums) {
            int n = nums.length;
            if (n < 3) {
                return 0;
            }
            int res = 0;
            Arrays.sort(nums);
            for (int i = 0; i < n - 2; i++) {
                for (int j = i + 1; j < n - 1; j++) {
                    int sum = nums[i] + nums[j];
                    int lo = j + 1, hi = n - 1;
                    while (lo < hi) {
                        int mid = (hi - lo + 1) / 2 + lo;
                        if (nums[mid] < sum) {
                            lo = mid;
                        } else {
                            hi = mid - 1;
                        }
                    }
                    if (nums[lo] < sum) {
                        // System.out.println(i + "_" + j +"_" + lo);
                        res += lo - j;
                    }
                }
            }
            return res;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums = new int[]{2,2,3,4};
        System.out.println(s.triangleNumber(nums));
    }
}
